import 'dart:async';

typedef Null OneArgFun(dynamic arg1);


class Tools {
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  static Function throttle(
    Future Function() func,
  ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }


  /// 函数防抖
  ///
  /// [func]: 要执行的方法
  /// [delay]: 要迟延的时长
  static Function debounce(
    OneArgFun func, [
    Duration delay = const Duration(milliseconds: 2000),
  ]) {
    Timer ? timer;
    Function target = (dynamic arg1) {
      if (timer?.isActive ?? false) {
        timer?.cancel();
      }
      timer = Timer(delay, () {
        Function.apply(func, [arg1]);
      });
    };
    return target;
  }
}